package app.im;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.example.menhoo.toollibrary.common.helper.AndroidFileUtil;
import com.example.menhoo.toollibrary.common.helper.DateUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.BitmapUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.SdCardUtil;
import com.example.menhoo.toollibrary.common.utils.SoundUtil;
import com.example.menhoo.toollibrary.common.utils.VibrateUtil;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.zejian.emotionkeyboard.fragment.EmotionMainFragment;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import adapter.MessageAdapter;
import app.ContactInfo;
import application.AppApplication;
import application.HttpUrlConstant;
import application.UIApplication;
import interfaces.IDownLoadListener;
import interfaces.IReturnObject;
import interfaces.IUpLoadListener;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.DownloadDbModel;
import model.IMCvnDBModel;
import model.IMFileModel;
import model.IMMessageDBModel;
import view.WaterMarkLayout;

/**
 * Created by yanglei on 16/12/26.
 */

public class IMDetails2 extends AppActivity implements View.OnClickListener {
    public static final int Open_GroupInfo = 0x1004;


    private String GroupID = null;
    private String Type = "couple";
    private String ID = null;
    private int UserCount = 0;
    private int UnreadCount = 0;
    private int DefCount = 20;
    private int Count = DefCount;
    private MessageAdapter adapter = null;
    int index = 0;
    int minCount = 7;
    String title;
    WrapContentLinearLayoutManager layoutManager;
    //
    private EmotionMainFragment emotionMainFragment;

    //

    private WaterMarkLayout waterMarkRelativeLayout;
    private RecyclerView listView;
    private SwipeRefreshLayout swipeLayout;
    private RelativeLayout bar_bottom;
    private LinearLayout rl_bottom;
    private Button btn_set_mode_voice;
    private Button btn_set_mode_keyboard;
    private LinearLayout btn_press_to_speak;
    private LinearLayout edittext_layout;
    private EditText et_sendmessage;
    private Button btn_emotion;
    private Button btn_more;
    private Button btn_send;
    private LinearLayout more;
    private LinearLayout ll_btn_container;
    private ImageView btn_take_picture;
    private ImageView btn_picture;
    private ImageView btn_location;
    private ImageView btn_video;
    private ImageView btn_file;
    private ImageButton rightBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //
        setContentView(R.layout.im_details2);
        initView();
        initEvent();
        getIntentData();
        setTitleName();
        setDownLoadReceiverHandle(new IDownLoadListener() {
            @Override
            public void DownloadStart(Context context, Intent intent, String url, String tag) {

            }

            @Override
            public void DownloadLoading(Context context, Intent intent, String url, long total, long current, String tag) {
                if (adapter != null) {
                    IMMessageDBModel item = adapter.getItemByUID(tag);
                    item.Progress = (long) (current*1.0f/total*100);
                    int len = adapter.getData().indexOf(item);
                    adapter.notifyItemChanged(len);
                }
            }

            @Override
            public void DownloadFinish(Context context, Intent intent, String url, String filePath, String tag) {

            }

            @Override
            public void DownloadCancelled(Context context, Intent intent, String url, String tag) {

            }

            @Override
            public void DownloadError(Context context, Intent intent, String url, String errorMsg, String tag) {

            }
        });

        setUploadLoadReceiverHandle(new IUpLoadListener() {
            @Override
            public void UploadStart(Context context, Intent intent, String url, String tag) {

            }

            @Override
            public void UploadLoading(Context context, Intent intent, String url, long total, long current, String tag) {
                if (adapter != null) {
                    IMMessageDBModel item = adapter.getItemByUID(tag);
                    if(item!=null){
                        item.Progress = (long) (current*1.0f/total*100);
                        int len = adapter.getData().indexOf(item);
                        adapter.notifyItemChanged(len);
                    }

                }
            }

            @Override
            public void UploadFinish(Context context, Intent intent, String url, String filePath, String webResult, String
                    tag) {

            }

            @Override
            public void UploadCancelled(Context context, Intent intent, String url, String tag) {
                if (adapter != null) {
                    IMMessageDBModel item = adapter.getItemByUID(tag);
                    if(item!=null){
                        try{
                            getDB().delete(item);
                        }
                        catch (Exception e){}
                        adapter.deleteByUID(tag);
                    }


                }
            }

            @Override
            public void UploadError(Context context, Intent intent, String url, String errorMsg, String tag) {
                if (adapter != null) {
                    IMMessageDBModel item = adapter.getItemByUID(tag);
                    item.SendStatus="2";
                    try{
                        getDB().update(item);
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                    int len = adapter.getData().indexOf(item);
                    adapter.notifyItemChanged(len);
                }
            }
        });

        setCustomRightButton(R.layout.fragment_im_right_btn);
        rightBtn = (ImageButton) findViewById(R.id.rightBtn);
        if (Type.toLowerCase().equalsIgnoreCase("group")) {

            rightBtn.setImageResource(R.mipmap.im_details_group);
            rightBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent it = new Intent(getApplicationContext(), IMGroupInfo.class);// 创建Intent对象
                    it.putExtra("ID", ID);
                    startActivityForResult(it, Open_GroupInfo);
                }
            });
        } else {

            rightBtn.setImageResource(R.mipmap.im_details_talk);
            rightBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent it = new Intent(getApplicationContext(), ContactInfo.class);// 创建Intent对象
                    it.putExtra("emplID", ID);
                    startActivity(it);
                }
            });
        }

        adapter = new MessageAdapter(this, this.Type);
        adapter.setOnItemClickLitener(new MessageAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                hideKeyboard();
                more.setVisibility(View.GONE);
                final IMMessageDBModel item = adapter.getItem(position);
                final IMFileModel fileModel = item.getFileInfo();
                if(fileModel!=null)
                {
                    if(BitmapUtil.isImage(fileModel.Ext))
                    {

                    }
                    else{

                        try {
                            DownloadDbModel downloadDbModel = getDB().findFirst(Selector.from(DownloadDbModel.class).where("tag", "=", item.UID));
                            if (downloadDbModel != null) {
                                if (downloadDbModel.isComplete) {
                                    try {
                                        //打开文件
                                        String path = downloadDbModel.path;
                                        startActivity(AndroidFileUtil.openFile(path));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        LogUtils.e(e.getMessage() + "");
                                    }
                                }

                            }
                            Map<String,String> parmFile= new HashMap<String,String>();
                            parmFile.put("attid", fileModel.ID);
                            parmFile.put("fileName", fileModel.Name);
                            String downloadUrl = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.Download,parmFile);

                            addDownloadQueue(item.UID, downloadUrl, UIApplication.getAppDownLoadPath
                                    (IMDetails2.this, downloadUrl), fileModel.Size+"", new IReturnObject() {
                                @Override
                                public void returnResult(Object result) {

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtils.e(e.getMessage() + "");
                        }




                    }
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
                final IMMessageDBModel item = adapter.getItem(position);
                if(!item.MessageType.equalsIgnoreCase("Text")){
                    return;
                }
                if(item!=null){
                    final android.app.Dialog dialog = showSimpleCustomDialogMessage(R.layout.im_message_dialog,true);
                    if(dialog!=null){
                        com.rey.material.widget.Button buttonCopy =(com.rey.material.widget.Button)dialog.findViewById(R.id.buttonCopy);
                        buttonCopy.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 将文本内容放到系统剪贴板里。
                                cm.setText(item.DecContext);

                                MessageUtil.showShortToast(IMDetails2.this,"复制成功");
                                dialog.dismiss();
                            }
                        });
                    }

                }
            }
        });
        adapter.setmOnSendAginLitener(new MessageAdapter.OnSendAginLitener() {
            @Override
            public void onSendTextAgin(int position) {
                IMMessageDBModel item = adapter.getItem(position);
                sendData(item);
            }

            @Override
            public void onSendImageAgin(int position) {
                IMMessageDBModel item = adapter.getItem(position);
                sendFile(item);
            }
        });
        layoutManager =new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        layoutManager.setReverseLayout(false);
        layoutManager.setSmoothScrollbarEnabled(true);
        //layoutManager.setStackFromEnd(true);//这个重要
        listView.setLayoutManager(layoutManager);
        listView.getItemAnimator().setChangeDuration(0);
        listView.setAdapter(adapter);
        listView.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                more.setVisibility(View.GONE);
                emotionMainFragment.close();
//                iv_emoticons_normal.setVisibility(View.VISIBLE);
//                iv_emoticons_checked.setVisibility(View.INVISIBLE);
//                emojiIconContainer.setVisibility(View.GONE);
//                btnContainer.setVisibility(View.GONE);
                return false;
            }
        });

        et_sendmessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                more.setVisibility(View.GONE);
            }
        });
        et_sendmessage.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    more.setVisibility(View.GONE);
                }
            }
        });
        et_sendmessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    btn_more.setVisibility(View.GONE);
                    btn_send.setVisibility(View.VISIBLE);
                } else {
                    btn_more.setVisibility(View.VISIBLE);
                    btn_send.setVisibility(View.GONE);
                }
                more.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        initEmotionMainFragment();

        SwipeRefreshLayout.OnRefreshListener listener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(index++);
            }
        };
        swipeLayout.setOnRefreshListener(listener);
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                //swipeLayout.setRefreshing(true);
            }
        });
        //listener.onRefresh();
        getData(index++);



    }

    private void getIntentData() {
        try { title = getIntent().getExtras().getString("Title");
        } catch (Exception e) { LogUtils.e(e.getMessage() + ""); }
        try { Type = getIntent().getExtras().getString("Type");
        } catch (Exception e) { LogUtils.e(e.getMessage() + ""); }
        try { GroupID = getIntent().getExtras().getString("GroupID");
        } catch (Exception e) { LogUtils.e(e.getMessage() + ""); }
        try { ID = getIntent().getExtras().getString("ID");
        } catch (Exception e) { LogUtils.e(e.getMessage() + ""); }
        try {
            UnreadCount = getIntent().getExtras().getInt("UnreadCount");
            if (UnreadCount > Count) {
                Count = UnreadCount;
            }
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
        try {
            UserCount = getIntent().getExtras().getInt("UserCount");
        } catch (Exception e) {
            UserCount = 0;
            LogUtils.e(e.getMessage() + "");
        }
    }

    private void initEvent() {
        btn_send.setOnClickListener(this);
        btn_more.setOnClickListener(this);
        btn_emotion.setOnClickListener(this);
        btn_take_picture.setOnClickListener(this);
        btn_picture.setOnClickListener(this);
        btn_file.setOnClickListener(this);
    }

    private void initView() {
        waterMarkRelativeLayout = (WaterMarkLayout)findViewById(R.id.waterMarkRelativeLayout);
        String name = AppApplication.getUser().EmplName;
        LogUtils.e("NAME:------------"+name);
        waterMarkRelativeLayout.setWaterMarkText(name);
        listView = (RecyclerView)findViewById(R.id.listView);
        swipeLayout = (SwipeRefreshLayout)findViewById(R.id.swipeLayout);
        bar_bottom = (RelativeLayout)findViewById(R.id.bar_bottom);
        rl_bottom = (LinearLayout)findViewById(R.id.rl_bottom);
        btn_set_mode_voice = (Button)findViewById(R.id.btn_set_mode_voice);
        btn_set_mode_keyboard = (Button)findViewById(R.id.btn_set_mode_keyboard);
        btn_press_to_speak = (LinearLayout)findViewById(R.id.btn_press_to_speak);
        edittext_layout = (LinearLayout)findViewById(R.id.edittext_layout);
        et_sendmessage = (EditText)findViewById(R.id.et_sendmessage);
        btn_more = (Button)findViewById(R.id.btn_more);
        btn_send = (Button)findViewById(R.id.btn_send);
        btn_emotion = (Button)findViewById(R.id.btn_emotion);
        more = (LinearLayout)findViewById(R.id.more);
        ll_btn_container = (LinearLayout)findViewById(R.id.ll_btn_container);
        btn_picture = (ImageView)findViewById(R.id.btn_picture);
        btn_take_picture = (ImageView)findViewById(R.id.btn_take_picture);
        btn_location = (ImageView)findViewById(R.id.btn_location);
        btn_video = (ImageView)findViewById(R.id.btn_video);
        btn_file = (ImageView)findViewById(R.id.btn_file);
    }

    @Override
    public void OnImMessage(Context context, IMMessageDBModel message) {
        if (adapter != null && message != null) {
            IMMessageDBModel model = message;

            try {
                if(model.MessageType.equalsIgnoreCase("File") && model.SenderID.equalsIgnoreCase(AppApplication.getUser().EmplID)){
                    IMFileModel fileInfo = model.getFileInfo();

                    IMMessageDBModel fItem = getDB().findById(IMMessageDBModel.class,fileInfo.ID);
                    if(fItem!=null){
                        model.UID=fItem.UID;
                        model.CreateTime=fItem.CreateTime;
                        getDB().update(model);


                    }
                    else{
                        if (model.GroupID.equalsIgnoreCase(GroupID)) {

                            addMessage(model);
                            confirmMsg(GroupID);
                        }
                        //播放声音
                        if (context != null) {
                            SoundUtil.play(context);
                            VibrateUtil.vibrateLong(context);
                        }
                        getDB().save(model);
                    }
                }
                else{
                    if (model.GroupID.equalsIgnoreCase(GroupID)) {

                        addMessage(model);
                        confirmMsg(GroupID);
                    }
                    //播放声音
                    if (context != null) {
                        SoundUtil.play(context);
                        VibrateUtil.vibrateLong(context);
                    }
                    getDB().save(model);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    @Override
    public void ImHasCvnUpdate(Context context, JSONObject data) {
        if (adapter != null) {
            try {
                data = data.getJSONObject("Conversation");
                String groupID = data.getString("groupID");
                String id = data.getString("id");
                String status = data.getString("status");
                String name = data.getString("name");
                int userCount = data.getInt("userCount");

                title = name;
                UserCount = userCount;
                setTitleName();
            } catch (Exception ex) {
                LogUtils.e(ex.getMessage() + "");
                ex.printStackTrace();

            }
        }
    }

    void setTitleName() {
        if (Type.toLowerCase().equalsIgnoreCase("group")) {
            setTitle(title + " (" + UserCount + ")");
        } else {
            setTitle(title);
        }

    }

    void hideKeyboard() {
        IMEHelper.hideIME(IMDetails2.this, true);
    }

    void toBottom() {
        if (adapter != null && adapter.getItemCount() > 0) {
            listView.scrollToPosition(adapter.getItemCount() - 1);
        }
    }

    void toBottom(int position) {
        if (adapter != null && adapter.getItemCount() > 0) {
            listView.scrollToPosition(position);
        }
    }

    void addMessage(IMMessageDBModel item) {
        try {
            if (!item.SendStatus.equalsIgnoreCase("0")) {
                getDB().save(item);
            }
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
            e.printStackTrace();
        }
        if (adapter != null) {
            adapter.add(item);
            toBottom();
            if(adapter.getItemCount()<minCount){
                layoutManager.setStackFromEnd(false);//这个重要
            }
            else{
                layoutManager.setStackFromEnd(true);//这个重要
            }
        }
    }

    /**
     * 得到数据
     */
    void getData(final int index) {
        hideAll();
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<IMMessageDBModel> list = new ArrayList<IMMessageDBModel>();
                try {
                    list = getDB().findAll(Selector.from(IMMessageDBModel.class).where("GroupID", "=", GroupID)
                            .and("CurrUserID", "=", AppApplication.getUser().EmplID)
                            .orderBy("CreateTime", true).offset(index * DefCount).limit(DefCount));
                    final List<IMMessageDBModel> list2 = list;
                    if (list != null && list.size() > 0) {
                        Collections.reverse(list);
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(list2.size()<minCount){
                                    layoutManager.setStackFromEnd(false);//这个重要
                                }
                                else{
                                    layoutManager.setStackFromEnd(true);//这个重要
                                }
                                if (index == 0) {
                                    adapter.add(list2);
                                    toBottom();
                                } else {
                                    adapter.add(0, list2);
                                    toBottom(list2.size()-1);
                                }
                            }
                        });


                    }
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                    e.printStackTrace();
                }


                swipeLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        swipeLayout.setRefreshing(false);
                    }
                });

                try {
                    //从网络获得数据
                    if (index == 0) {
                        requestData(DateUtil.DateToString(DateUtil.Now(), DateUtil.TimeFormatOne), Count + "", true);
                    } else {
                        if (adapter != null && adapter.getItemCount() > 0) {
                            if (list.size() < DefCount) {
                                IMMessageDBModel item = adapter.getItem(0);
                                requestData(DateUtil.DateToString(item.CreateTime, DateUtil.TimeFormatOne), (Count - list.size()) + "", false);
                            }

                        }
                    }

                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 请求会话数据
     */
    private void requestData(final String time, final String count, final boolean desc) {
        HandlerUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setTitle("获取中...");
            }
        });

        HandlerUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                RequestParams params = new RequestParams();
                params.addQueryStringParameter("__session__", AppApplication.getSession());
                params.addQueryStringParameter("groupID", GroupID);
                params.addQueryStringParameter("time", time);
                params.addQueryStringParameter("count", count);
                HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetMessageListByLastTime),
                        params, new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                String result = responseInfo.result;
                                if (result != null) {
                                    LogUtils.e("回话消息："+result);
                                    List<IMMessageDBModel> list = new ArrayList<IMMessageDBModel>();
                                    try {
                                        JSONObject jsonObject = new JSONObject(result);
                                        if (jsonObject.getBoolean("Succeed")) {
                                            JSONArray appArray = jsonObject.getJSONArray("Data");
                                            for (int i = 0; i < appArray.length(); i++) {
                                                JSONObject data = appArray.getJSONObject(i);
                                                IMMessageDBModel model = new IMMessageDBModel(data);

                                                try {
                                                    long re = getDB().count(Selector.from(IMMessageDBModel.class).where("ID", "=", model.ID));
                                                    if (re == 0) {
                                                        if(model.MessageType.equalsIgnoreCase("File") && model.SenderID.equalsIgnoreCase(AppApplication.getUser().EmplID)){
                                                            IMFileModel fileInfo = model.getFileInfo();
                                                            if(fileInfo!=null){
                                                                IMMessageDBModel fItem = getDB().findById(IMMessageDBModel.class,fileInfo.ID);
                                                                if(fItem!=null){
                                                                    model.UID=fItem.UID;
                                                                    model.CreateTime=fItem.CreateTime;
                                                                    getDB().update(model);

                                                                    IMMessageDBModel item = adapter.getItemByUID(model.UID);
                                                                    item.Context=model.Context;
                                                                    item.MessageType=model.MessageType;
                                                                    item.Device = model.Device;
                                                                    item.DecContext = model.DecContext;
                                                                    item.Progress =100;
                                                                    int len = adapter.getData().indexOf(item);
                                                                    adapter.notifyItemChanged(len);
                                                                }
                                                                else{
                                                                    list.add(model);
                                                                }
                                                            }

                                                        }
                                                        else{
                                                            list.add(model);
                                                        }

                                                    }

                                                } catch (DbException e) {
                                                    e.printStackTrace();
                                                }

                                            }
                                            if (list.size() > 0) {
                                                if(list.size()<minCount){
                                                    layoutManager.setStackFromEnd(false);//这个重要
                                                }
                                                else{
                                                    layoutManager.setStackFromEnd(true);//这个重要
                                                }
                                                if (desc) {
                                                    adapter.add(list);
                                                    toBottom();
                                                } else {
                                                    adapter.add(0, list);
                                                    toBottom(list.size()-1);
                                                }

                                                getDB().saveAll(list);
                                                if (list.size() > DefCount) {
                                                    Count = DefCount;
                                                }
                                            }

                                        }

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                HandlerUtil.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        setTitleName();
                                    }
                                });
                                confirmMsg(GroupID);
                            }

                            @Override
                            public void onFailure(HttpException error, String msg) {
                                HandlerUtil.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        setTitleName();
                                    }
                                });
                                confirmMsg(GroupID);
                            }
                        });


            }
        });



    }

    private void confirmMsg(final String groupID) {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("groupID", groupID);
        params.addQueryStringParameter("time", DateUtil.Now().getTime()+"");

        HttpSend(HttpMethod.GET, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.ConfirmMsg),
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        if (result != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {

                                    IMCvnDBModel item = getDB().findById(IMCvnDBModel.class, groupID);
                                    item.unreadCount = 0;
                                    getDB().update(item);

                                    //MessageUtil.showShortToast(IMDetails2.this,"confirmMsg:成功");
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        //MessageUtil.showShortToast(IMDetails2.this,"confirmMsg:"+msg+":"+HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.ConfirmMsg));
                    }
                });

    }

    void sendData(final IMMessageDBModel item) {
        item.SendStatus="1";
        adapter.notifyDataSetChanged();

        String text = item.Context;
        try {
            text = URLEncoder.encode(text, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        if (Type.toLowerCase().equalsIgnoreCase("group")) {
            params.addQueryStringParameter("id", GroupID);
        } else {
            params.addQueryStringParameter("id", ID);
        }
        params.addQueryStringParameter("type", Type);
        params.addQueryStringParameter("text", text);
        params.addQueryStringParameter("device", "android");
        params.addQueryStringParameter("connectionID", AppApplication.getSignalrID());
        HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.SendText),
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getBoolean("Succeed")) {
                                IMMessageDBModel m = adapter.getItemByUID(item.UID);
                                if (m != null) {
                                    m.SendStatus = "0";
                                    adapter.notifyDataSetChanged();
                                }

                                JSONObject data = jsonObject.getJSONObject("Data");
                                IMMessageDBModel message = new IMMessageDBModel(data);
                                message.UID = m.UID;
                                getDB().update(message);

                                IMCvnDBModel item = getDB().findById(IMCvnDBModel.class, GroupID);
                                if (Type.toLowerCase().equalsIgnoreCase("group")) {
                                    item.lastMessage = AppApplication.getUser().EmplName + ": " + message.DecContext;
                                } else {
                                    item.lastMessage = message.DecContext;
                                }
                            } else {
                                IMMessageDBModel m = adapter.getItem(item.ID);
                                if (m != null) {
                                    m.SendStatus = "2";
                                    getDB().update(m);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            try{
                                IMMessageDBModel m = adapter.getItem(item.ID);
                                if (m != null) {
                                    m.SendStatus = "2";
                                    getDB().update(m);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                            catch (Exception ex2){
                                ex2.printStackTrace();
                            }

                        }


                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        //MessageUtil.showShortToast(IMDetails2.this, msg);
                        try{
                            IMMessageDBModel m = adapter.getItem(item.ID);
                            if (m != null) {
                                m.SendStatus = "2";
                                getDB().update(m);
                                adapter.notifyDataSetChanged();
                            }
                        }
                        catch (Exception ex2){
                            ex2.printStackTrace();
                        }
                    }
                });
    }

    void sendMessage(String text) {
        Log.e("发送消息" , "发送信息："+text);

        final String F_id = UUID.randomUUID().toString();
        IMMessageDBModel im = new IMMessageDBModel();
        im.MessageType = "Text";
        im.SenderType = "Employee";
        im.Context = text;
        im.DecContext = text;
        im.ID = F_id;
        im.GroupID = GroupID;
        im.CreateTime = DateUtil.Now();
        im.SenderID = AppApplication.getUser().EmplID;
        im.CurrUserID = im.SenderID;
        im.Device = "android";
        im.SendStatus = "1";
        addMessage(im);

        sendData(im);
    }

    void showMore(boolean F) {
        if (F) {
            more.setVisibility(View.VISIBLE);
            emotionMainFragment.close();
        } else {
            more.setVisibility(View.GONE);
        }
    }

    private File cameraFile;
    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_LOCAL = 19;
    public static final int REQUEST_CODE_SELECT_FILE = 24;

    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!SdCardUtil.isSdCardAvailable()) {
            Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        cameraFile = new File(AppApplication.getAppCachePath(IMDetails2.this), System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
                        MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * 选择文件
     */
    private void selectFileFromLocal() {
        Intent intent = null;
        intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 从图库获取图片
     */
    public void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == Open_GroupInfo) {
            try {
                boolean isClose = data.getBooleanExtra("IsClose",false);
                if(isClose){
                    onBackPressed();
                }

                String GroupName = data.getStringExtra("GroupName");
                final int Count = data.getIntExtra("UserCount", 0);
                title = GroupName;
                UserCount = Count;
                setTitleName();

                HandlerUtil.runOnUiThreadDelay(new Runnable() {
                    @Override
                    public void run() {
                        requestData(DateUtil.DateToString(DateUtil.Now(), DateUtil.TimeFormatOne), Count + "", true);
                        HandlerUtil.runOnUiThreadDelay(new Runnable() {
                            @Override
                            public void run() {
                                confirmMsg(GroupID);
                            }
                        },500);
                    }
                },500);

            } catch (Exception e) {
                LogUtils.e(e.getMessage() + "");
                e.printStackTrace();
            }

        } else if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
            if (cameraFile != null && cameraFile.exists()) {
                LogUtils.e("cameraFile.getAbsolutePath()------>>>>" + cameraFile.getAbsolutePath());
                IMMessageDBModel im = new IMMessageDBModel();
                im.MessageType = "UploadImg";
                im.SenderType = "Employee";
                im.Context = cameraFile.getAbsolutePath();
                im.DecContext = cameraFile.getAbsolutePath();
                im.ID = "";
                im.GroupID = GroupID;
                im.CreateTime = DateUtil.Now();
                im.SenderID = AppApplication.getUser().EmplID;
                im.CurrUserID = im.SenderID;
                im.Device = "android";
                im.SendStatus = "1";
                addMessage(im);

                sendFile(im);
            }

        }
        else if(requestCode == REQUEST_CODE_LOCAL) { // 发送照片
            if(data!=null){
                Uri selectedImage = data.getData();
                if(selectedImage!=null){
                    Cursor cursor = getContentResolver().query(selectedImage, null, null,
                            null, null);
                    if (cursor != null) {
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex("_data");
                        String picturePath = cursor.getString(columnIndex);
                        cursor.close();
                        cursor = null;

                        if (picturePath == null || picturePath.equals("null")) {
                            Toast toast = Toast.makeText(IMDetails2.this, "找不到图片", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            return;
                        }

                        IMMessageDBModel im = new IMMessageDBModel();
                        im.MessageType = "UploadImg";
                        im.SenderType = "Employee";
                        im.Context = picturePath;
                        im.DecContext = picturePath;
                        im.ID = "";
                        im.GroupID = GroupID;
                        im.CreateTime = DateUtil.Now();
                        im.SenderID = AppApplication.getUser().EmplID;
                        im.CurrUserID = im.SenderID;
                        im.Device = "android";
                        im.SendStatus = "1";
                        addMessage(im);
                        sendFile(im);
                    } else {
                        File file = new File(selectedImage.getPath());
                        if (!file.exists()) {
                            Toast toast = Toast.makeText(IMDetails2.this, "找不到图片", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            return;

                        }
                        IMMessageDBModel im = new IMMessageDBModel();
                        im.MessageType = "UploadImg";
                        im.SenderType = "Employee";
                        im.Context = file.getAbsolutePath();
                        im.DecContext = file.getAbsolutePath();
                        im.ID = "";
                        im.GroupID = GroupID;
                        im.CreateTime = DateUtil.Now();
                        im.SenderID = AppApplication.getUser().EmplID;
                        im.CurrUserID = im.SenderID;
                        im.Device = "android";
                        im.SendStatus = "1";
                        addMessage(im);
                        sendFile(im);
                    }
                }
            }

        }
        else if(requestCode == REQUEST_CODE_SELECT_FILE) { // 发送文件
            if(data!=null){
                Uri selectedImage = data.getData();
                if(selectedImage!=null){
                    File file = new File(selectedImage.getPath());
                    if (!file.exists()) {
                        Toast toast = Toast.makeText(IMDetails2.this, "找不到文件", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        return;

                    }
                    IMMessageDBModel im = new IMMessageDBModel();
                    im.MessageType = "UploadFile";
                    im.SenderType = "Employee";
                    im.Context = file.length()+"";
                    im.DecContext = file.getAbsolutePath();
                    im.ID = "";
                    im.GroupID = GroupID;
                    im.CreateTime = DateUtil.Now();
                    im.SenderID = AppApplication.getUser().EmplID;
                    im.SenderName = file.getName();
                    im.CurrUserID = im.SenderID;
                    im.Device = "android";
                    im.SendStatus = "1";
                    addMessage(im);
                    sendFile(im);
                }
            }
        }
        //
    }

    void sendFile(IMMessageDBModel im){
        IMMessageDBModel item = adapter.getItemByUID(im.UID);
        item.SendStatus="1";
        int len = adapter.getData().indexOf(item);
        adapter.notifyItemChanged(len);


        Map<String, String> parm = new HashMap<String, String>();
        parm.put("id", im.UID);
        parm.put("__session__", AppApplication.getSession());
        parm.put("groupID", GroupID);
        parm.put("device", "android");
        String url = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.Plupload, parm);
        getDownLoadService().upload(im.UID, url, im.DecContext);
    }


    @Override
    public void onBackPressed() {

        super.onBackPressed();
        hideKeyboard();
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onStop() {
        super.onStop();

    }

    /**
     * 初始化表情面板
     */
    public void initEmotionMainFragment(){
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT,false);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN,true);
        //替换fragment
        //创建修改实例
        emotionMainFragment =EmotionMainFragment.newInstance(EmotionMainFragment.class,bundle);
        emotionMainFragment.bindToContentView(et_sendmessage);
        FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main,emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i == R.id.btn_send) {
            String text = et_sendmessage.getText().toString();
            et_sendmessage.setText("");
            if (TextUtils.isEmpty(text)) {
                return;
            }
            sendMessage(text);
        } else if (i == R.id.btn_more) {
            showMore(true);
            IMEHelper.hideIME(IMDetails2.this, true);
        } else if (i == R.id.btn_emotion) {
            emotionMainFragment.open();
        } else if (i == R.id.btn_take_picture) {
            selectPicFromCamera();
        } else if (i == R.id.btn_picture) {
            selectPicFromLocal();
        } else if (i == R.id.btn_file) {
            selectFileFromLocal();
        }

    }

    public class WrapContentLinearLayoutManager extends LinearLayoutManager {
        public WrapContentLinearLayoutManager(Context context) {
            super(context);
        }

        public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
}
